import {
  useState,
  useRef,
  useEffect,
  useInsertionEffect,
  useLayoutEffect,
} from "react";

function App() {
  const h1Ref = useRef();
  const divRef = useRef();
  const [show, setShow] = useState(true);

  useLayoutEffect(() => {
    // console.log("useEffect", h1Ref.current);
    if (!divRef.current) return;
    // 操作DOM的样式
    divRef.current.style.marginTop = "50px";
  }, [show]);

  // useLayoutEffect(() => {
  //   console.log("useLayoutEffect", h1Ref.current);
  // }, []);

  // 特点：在DOM改变之后触发，所以无法获取到最新真实的DOM
  //      主要用于一些第三方库，提供 css in js 操作的库。
  // useInsertionEffect(() => {
  //   console.log("useInsertionEffect", h1Ref.current);
  // }, []);

  return (
    <div>
      <h1 ref={h1Ref}>App</h1>

      <button onClick={() => setShow((show) => !show)}>Toggle</button>

      {show && (
        <div
          ref={divRef}
          style={{ width: 100, height: 100, backgroundColor: "green" }}
        ></div>
      )}
    </div>
  );
}

export default App;
